﻿using AntdUI;
using Serilog;
using System.Diagnostics;
using System.Text.RegularExpressions;
using WorkTool2.Classes.Data;
using WorkTool2.Helpers;

namespace WorkTool2.Controls
{
    public partial class Base64AndFileConversion : UserControl
    {
        private Form form;

        public Base64AndFileConversion(Form _form)
        {
            form = _form;
            InitializeComponent();
            InitRichTextBox();
        }

        #region RichTextBox

        private Color borderColorUnFocusWhite = Color.FromArgb(220, 220, 220);
        private Color borderColorUnFocusBlack = Color.FromArgb(40, 40, 40);
        private Color borderColorFocusWhite = Color.FromArgb(160, 200, 255);
        private Color borderColorFocusBlack = Color.FromArgb(50, 89, 158);

        private void InitRichTextBox()
        {
            SettingColor();
            richTextBox_ClearBtn.Hide();
            richTextBox.MouseEnter += FocusColor;
            richTextBox.MouseLeave += UnFocusColor;
            richTextBox.GotFocus += (s, e) =>
            {
                FocusColor(s, e);
                richTextBox.MouseLeave -= UnFocusColor;
            };
            richTextBox.Leave += (s, e) =>
            {
                UnFocusColor(s, e);
                richTextBox.MouseLeave += UnFocusColor;
            };
            richTextBox.Resize += (s, e) =>
            {
                UpdateClearButtonPosition();
            };
            UpdateClearButtonPosition();
            form.ForeColorChanged += (s, e) =>
            {
                SettingColor();
            };
        }

        private void SettingColor()
        {
            if (Config.IsDark)
            {
                richTextBox.BackColor = Color.Black;
                richTextBox.ForeColor = Color.White;
                richTextBox_ClearBtn.OriginalBackColor = Color.Black;
                richTextBox_Border.BackColor = borderColorUnFocusBlack;
            }
            else
            {
                richTextBox.BackColor = Color.White;
                richTextBox.ForeColor = Color.Black;
                richTextBox_ClearBtn.OriginalBackColor = Color.White;
                richTextBox_Border.BackColor = borderColorUnFocusWhite;
            }
        }

        private void FocusColor(object? s, EventArgs e)
        {
            richTextBox_ClearBtn.Show();
            richTextBox_Border.BackColor = Config.IsDark ? borderColorFocusBlack : borderColorFocusWhite;
        }

        private void UnFocusColor(object? s, EventArgs e)
        {
            richTextBox_ClearBtn.Hide();
            richTextBox_Border.BackColor = Config.IsDark ? borderColorUnFocusBlack : borderColorUnFocusWhite; // 边框颜色
        }

        private void UpdateClearButtonPosition()
        {
            richTextBox_ClearBtn.Location = new Point(
                richTextBox_Border.Right - richTextBox_ClearBtn.Width - 19,
                richTextBox_Border.Top + 4
            );
            richTextBox_ClearBtn.BringToFront();
        }

        private void richTextBox_ClearBtn_Click(object sender, EventArgs e)
        {
            richTextBox.Clear();
            richTextBox.Invalidate();
            richTextBox.Focus();
            richTextBox.MouseLeave -= UnFocusColor;
        }

        #endregion

        private void uploadDragger_DragChanged(object sender, StringsEventArgs e)
        {
            var filePath = e.Value[0];
            var fileName = "";
            Spin.open(form, "正在处理中，请耐心等候...",
                config =>
                {
                    try
                    {
                        var fileInfo = new FileInfo(filePath);
                        if (fileInfo.Exists)
                        {
                            fileName = fileInfo.Name;
                            var base64String = File.ReadAllText(filePath).Trim();
                            if (IsBase64String(base64String))
                            {
                                richTextBox.InvokeIfRequired(() =>
                                {
                                    richTextBox.Text = base64String;
                                });
                            }
                            uploadDragger.TextDesc = fileName;
                            uploadDragger.Tag = filePath;
                        }
                        else
                        {
                            Modal.open(form, "错误", "文件不存在", TType.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        Modal.open(form, "错误", $"获取文件出错: {ex.Message}", TType.Error);
                        Log.Error(ex, ex.Message);
                    }
                },
                () =>
                {
                }
            );
        }

        private void base64_btn_Click(object sender, EventArgs e)
        {
            Spin.open(form, "正在处理中，请耐心等候...",
                 config =>
                {
                    try
                    {
                        var base64String = string.Empty;
                        richTextBox.InvokeIfRequired(() =>
                        {
                            base64String = richTextBox.Text.Trim();
                        });
                        if (!string.IsNullOrEmpty(base64String))
                        {
                            string fileType = FileTypeDetector.GetFileTypeFromBase64(base64String);
                            if (fileType.Equals("unknown"))
                            {
                                fileType = FileTypeDetector.GetFileTypeFromBase64(base64String);
                            }
                            string extension = FileTypeDetector.GetFileExtensionFromMimeType(fileType);
                            var filePath = Path.Combine(SettingsHelper._fileSettings.SaveFolder, $"Base64-{DateTime.Now:yyyyMMddHHmmss}{extension}");
                            byte[] fileBytes = Convert.FromBase64String(base64String);
                            File.WriteAllBytes(filePath, fileBytes);
                            uploadDragger.TextDesc = "";
                            uploadDragger.Tag = "";
                            if (new Modal.Config(form, "是否打开文件？", $"文件已保存至：{filePath}", TType.Success)
                            {
                                OnButtonStyle = (id, btn) =>
                                {
                                    btn.BackExtend = "135, #6253E1, #04BEFE";
                                },
                                CancelText = "否",
                                OkText = "是"
                            }.open() == DialogResult.OK)
                            {
                                if (ToolHelper._images.Contains(extension))
                                {
                                    Preview.open(new Preview.Config(form, Image.FromFile(filePath)));
                                }
                                else
                                {
                                    Process.Start(new ProcessStartInfo
                                    {
                                        FileName = filePath,
                                        UseShellExecute = true
                                    });
                                }
                            }
                            (form as Main).AddHistoryData(new HistoryData("Base64&文件互转", filePath)).ConfigureAwait(false);
                        }
                        else
                        {
                            new Modal.Config(form, "错误", "请先上传内容为Base64的文件或输入Base64字符串", TType.Error)
                            {
                                CancelText = null,
                                OkType = TTypeMini.Error,
                                OkText = "知道了"
                            }.open();
                        }
                    }
                    catch (Exception ex)
                    {
                        Modal.open(form, "错误", $"Base64转文件失败: {ex.Message}", TType.Error);
                        Log.Error(ex, ex.Message);
                    }
                },
                () => { }
            );
        }

        private void file_btn_Click(object sender, EventArgs e)
        {
            Spin.open(form, "正在处理中，请耐心等候...",
                config =>
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(uploadDragger.TextDesc))
                        {
                            using var fileStream = new FileStream(uploadDragger.Tag.ToString(), FileMode.Open, FileAccess.Read);
                            byte[] bytes = new byte[fileStream.Length];
                            fileStream.Read(bytes, 0, (int)fileStream.Length);
                            richTextBox.InvokeIfRequired(() =>
                            {
                                richTextBox.Text = Convert.ToBase64String(bytes);
                            });
                            uploadDragger.InvokeIfRequired(() =>
                            {
                                uploadDragger.TextDesc = "";
                                uploadDragger.Tag = "";
                            });
                        }
                        else
                        {
                            new Modal.Config(form, "错误", "请先上传文件", TType.Error)
                            {
                                CancelText = null,
                                OkType = TTypeMini.Error,
                                OkText = "知道了"
                            }.open();
                        }
                    }
                    catch (Exception ex)
                    {
                        Modal.open(form, "错误", $"文件转Base64格式失败: {ex.Message}", TType.Error);
                        Log.Error(ex, ex.Message);
                    }
                },
                () => { }
            );
        }

        private static bool IsBase64String(string input)
        {
            if (string.IsNullOrEmpty(input) || input.Length % 4 != 0)
                return false;

            // Base64正则表达式模式
            string pattern = @"^[a-zA-Z0-9\+/]*={0,3}$";
            return Regex.IsMatch(input, pattern);
        }
    }
}